package br.great.classes;

/**
 * PhotoMap
 * Copyright (c) 2007-2008 STEAMER - LIG, All rights reserved.
 */
import java.io.File;
import java.awt.image.*;
import java.awt.Image;
import java.awt.image.AffineTransformOp;
import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;

/*** @param fromdir the directory of the images
 * @param todir the directory of save the images
 * @param imgfile the image resource
 * @param sysimgfile the name of the image traded**/
public class TradeImage {
public float[] createThumbnail(String imgfile, String todir, String sysimgfile) throws Exception {
        //ext is the format of the image gif JPG ou png
        float[] sa = new float[2];
        String ext = "";
        double Ratio = 0.0;
        
        // fromdir,imgfile
        File F = new File(imgfile);
        if (!F.isFile()) {
            throw new Exception(F + " is not image file error in CreateThumbnail!");
        }
        
        ext = "png";
        File ThF = new File(todir, sysimgfile + "." + ext);
        BufferedImage Bi = ImageIO.read(F);
        int width = Bi.getWidth();
        int height = Bi.getHeight();
        
        Image subI;
        if (width <= 400 && height <= 400) {
            if (width > height) {
                subI = Bi.getSubimage(width / 2 - height / 2, 0, height, height);
                Ratio = 75.0 / height;
            } else {
                subI = Bi.getSubimage(0, height / 2 - width / 2, width, width);
                Ratio = 75.0 / width;
            }
            sa[1] = width;
            sa[0] = height;
        } else {
            if (width > height) {
                subI = Bi.getSubimage(width / 2 - height / 2, 0, height, height);
                Ratio = 75.0 / height;
                
                sa[1] = 400;
                sa[0] = ((float) height / width) * 400;
            } else {
                subI = Bi.getSubimage(0, height / 2 - width / 2, width, width);
                Ratio = 75.0 / width;
                
                sa[1] = ((float) width / height) * 400;
                sa[0] = 400;
            }
        }
        
        AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(Ratio, Ratio), null);
        subI = op.filter((BufferedImage) subI, null);
        try {
            ImageIO.write((BufferedImage) subI, ext, ThF);
        } catch (Exception ex) {
            throw new Exception(" ImageIo.write error in CreatThum.: " + ex.getMessage());
        }
        return sa;
    }
//        public static void main(String[] args){
//        try {
//            TradeImage ti = new TradeImage();
//            float[] ia = ti.CreateThumbnail("c:\\abc.jpg", "e:\\","traded");
//            System.out.println(ia[0]+" "+ia[1]);
//            
//            //System.out.println(ti.isJpg("abc.jpg"));   
//        } catch (Exception ex) {
//            Logger.getLogger(TradeImage.class.getName()).log(Level.SEVERE, null, ex);
//        }
//    }    
}
